package com.sen.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.AsyncContext;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 异步Filter
 * 参考：http://www.blogjava.net/yongboy/archive/2011/01/15/346203.html
 */
public class TestFilterAsync implements Filter {

    /**
     * Default constructor. 
     */
    public TestFilterAsync() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		// pass the request along the filter chain
	    //response.setContentType("text/html;charset=UTF-8");  
		chain.doFilter(request, response);
		/*PrintWriter out = response.getWriter();  
        out.println("进入Servlet的时间：" + new Date() + ".");  
        out.flush();  
        
        request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
        //在子线程中执行业务调用，并由其负责输出响应，主线程退出  
        final AsyncContext ctx = request.startAsync();  
        ctx.setTimeout(200000);  
        new Work(ctx).start();  
        out.println("结束Servlet的时间：" + new Date() + ".");  
        out.flush();  */
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}
	
	/*class Work extends Thread{  
	    private AsyncContext context;  
	      
	    public Work(AsyncContext context){  
	        this.context = context;  
	    }  
	    @Override  
	    public void run() {  
	        try {  
	            Thread.sleep(5000);//让线程休眠2s钟模拟超时操作  
	            PrintWriter wirter = context.getResponse().getWriter();           
	            wirter.write("延迟输出");  
	            wirter.flush();  
	            context.complete();  
	        } catch (InterruptedException e) {  
	              
	        } catch (IOException e) {  
	              
	        }  
	    }  
	}*/ 

}
